﻿using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Net;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Navigation;
using FirstFloor.Documents.Controls;
using FirstFloor.Documents.IO;
using FirstFloor.Documents.IO.DotNetZip;

namespace SampleBrowser.Views
{
    public partial class SampleLoadingStrategies : Page
    {
        public SampleLoadingStrategies()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);

            // properly clears the datasource and closes the package reader
            this.DataSource.PackageReader = null;
        }

        private void DataSource_LoadError(object sender, ErrorEventArgs e)
        {
            new ErrorWindow(e.Error).Show();
        }

        private void cmbLoadFrom_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            switch (this.cmbLoadFrom.SelectedIndex) {
                case 0: LoadFromIsolatedStorage(); break;
                case 1: LoadFromLocalDisk(); break;
                case 2: LoadFromWebAllInOnce(); break;
                case 3: LoadFromWebJustInTime(); break;
                case 4: LoadFromWCFService(); break;
            }
        }

        private bool EnsureDocumentInIsoStorage()
        {
            var iso = IsolatedStorageFile.GetUserStoreForApplication();

            if (iso.Quota < (16 << 19) && !iso.IncreaseQuotaTo(16 << 19)) {
                return false;
            }

            if (!iso.FileExists("TestDocument.xps")) {
                // first save XPS document to isostore
                var resource = Application.GetResourceStream(new Uri("Assets/Documents/TestDocument.xps", UriKind.Relative));
                using (resource.Stream) {
                    using (var file = iso.CreateFile("TestDocument.xps")) {
                        resource.Stream.CopyTo(file);
                    }
                }
            }
            return true;
        }

        private void LoadFromIsolatedStorage()
        {
            try {
                // ensure an xps document exists in local isolated storage
                if (!EnsureDocumentInIsoStorage()) {
                    return;
                }

                var iso = IsolatedStorageFile.GetUserStoreForApplication();
                var stream = iso.OpenFile("TestDocument.xps", FileMode.Open, FileAccess.Read);

                // create new package reader
                this.DataSource.PackageReader = new DotNetZipPackageReader(stream);
            }
            catch (IsolatedStorageException e) {
                // failed to init isolated storage
                new ErrorWindow(e).Show();
            }
        }

        private void LoadFromLocalDisk()
        {
            // open file dialog
            var dlg = new OpenFileDialog();
            dlg.Filter = "XPS Documents (*.xps)|*.xps|All Files (*.*)|*.*";
            dlg.Multiselect = false;
            if (true == dlg.ShowDialog()) {
                // get file stream
                var stream = dlg.File.OpenRead();

                // create new package reader
                this.DataSource.PackageReader = new DotNetZipPackageReader(stream);
            }
        }

        private void LoadFromWebAllInOnce()
        {
            // load the entire XPS document in once using a WebClient
            var webClient = new WebClient();
            webClient.OpenReadCompleted += (o, e) => {
                if (e.Error != null) {
                    new ErrorWindow(e.Error).Show();
                }
                else if (!e.Cancelled) {
                    // create new package reader
                    this.DataSource.PackageReader = new DotNetZipPackageReader(e.Result);
                }
            };

            // loads the sample XPS document from the web
            webClient.OpenReadAsync(new Uri(HtmlPage.Document.DocumentUri, "Documents/TestDocument.xps"));
        }

        private void LoadFromWebJustInTime()
        {
            // use the web package reader to load XPS document in parts just in time
            // the package uri refers to a document service capable of serving document parts
            // see DocumentService.ashx source for more details.

            var packageUri = WebPackageReader.CreateAbsoluteBaseUri("DocumentService.ashx?TestDocument.xps");

            // create new package reader
            this.DataSource.PackageReader = new WebPackageReader2(packageUri);
        }

        private void LoadFromWCFService()
        {
            // use the WcfPackageReader to load XPS documents in parts just in time using a WCF service
            // see DocumentWcfService.svc for more details
            var serviceUri = WebPackageReader.CreateAbsoluteBaseUri("DocumentWcfService.svc");

            this.DataSource.PackageReader = new WcfPackageReader(serviceUri, "TestDocument.xps");
        }
    }
}
